import { changeState, childrenById, deleteDict } from "@/api/dict";
import { message } from "@/utils/message";
import { onMounted, reactive, ref } from "vue";
import { FormInstance } from "element-plus";
import { handleTree } from "@/utils/tree";
import { DictModel } from "@/api/model/dictModel";

export function useColumns() {
  const form = reactive<DictModel>({});
  const dataList = ref([]);
  const loading = ref(true);
  const s_loading = ref(false);
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      hide: ({ checkList }) => !checkList.includes("勾选列"),
    },
    {
      label: "序号",
      type: "index",
      width: 60,
      hide: ({ checkList }) => !checkList.includes("序号列"),
    },
    {
      label: "字典名称",
      prop: "label",
      align: "left",
      width: 150,
    },
    {
      label: "字典代码",
      prop: "code",
    },
    {
      label: "排序",
      prop: "sort",
      width: 60,
    },
    {
      label: "状态",
      prop: "state",
      width: 80,
      cellRenderer: ({ row, props }) => (
        <el-switch
          v-model={row.state}
          size={props.size}
          inline-prompt
          loading={s_loading.value}
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          active-text="启用"
          inactive-text="禁用"
          onChange={() => dictStateChange(row)}
        />
      ),
    },
    {
      label: "字典描述",
      prop: "description",
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation",
    },
  ];

  const dictStateChange = row => {
    s_loading.value = true;
    changeState(row.id, row.state)
      .then(res => {
        if (res) {
          message("状态修改成功", { type: "success" });
        } else {
          message("状态修改失败", { type: "error" });
        }
      })
      .catch(e => {
        message(e.message, { type: "error" });
      })
      .finally(() => {
        s_loading.value = false;
      });
  };

  const formRef = ref<FormInstance>();
  const tableRef = ref();
  const loadMap = new Map();

  function handleDelete(row) {
    deleteDict(row.id)
      .catch(err => {
        message(err.message, { type: "error" });
      })
      .finally(() => {
        reloadChildren(row.parentId);
      });
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const data = await childrenById("0").catch(err => {
      message(err.message, { type: "error" });
    });
    dataList.value = handleTree(data as any);
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  async function loadChildren(
    row: DictModel,
    treeNode: unknown,
    resolve: (date: DictModel[]) => void
  ) {
    //将获取到的节点数据添加到loadMap变量中
    loadMap.set(row.id, { row, treeNode, resolve });
    const data = await childrenById(row.id);
    resolve(data);
  }

  async function reloadChildren(pid: string) {
    const { row, treeNode, resolve } = loadMap.get(pid);
    //清空节点的数据
    tableRef.value.getTableRef().store.states.lazyTreeNodeMap[pid] = [];
    loadChildren(row, treeNode, resolve);
  }

  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    columns,
    form,
    dataList,
    loading,
    formRef,
    tableRef,
    handleDelete,
    reloadChildren,
    handleSelectionChange,
    onSearch,
    loadChildren,
    resetForm,
  };
}
